/*
 * Copyright (C) 2007 BitLab.com.ua
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ua.com.bitlab.rsprocessor;



import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.InvocationTargetException;

/**
 * @author Yaroslav Yermak
 * @version 1.0, Mar 7, 2007
 */
public class Chain {
// ------------------------------ FIELDS ------------------------------

    private Map<String, RsProcessor> map = new HashMap<String, RsProcessor>();
    private Map<String, RsProcessor> copy;

    private Map<Class, Map<Integer, Object>> cache = new HashMap<Class, Map<Integer, Object>>();

// --------------------- GETTER / SETTER METHODS ---------------------

    public Map<Class, Map<Integer, Object>> getCache() {
        return cache;
    }

// -------------------------- OTHER METHODS --------------------------

    public void addProcessor(String primaryKey, RsProcessor rsProcessor) {
        map.put(primaryKey, rsProcessor);
    }

    public Object handleBean(ResultSet rs, String primaryKey) throws SQLException {
        return processBean(rs, primaryKey, null);
    }

    public Object processBean(ResultSet rs, String primaryKey, Object entity) throws SQLException {
        if (rs.getObject(primaryKey) == null) {
            return null;
        }

        RsProcessor rsProcessor = copy.remove(primaryKey);

        if (rsProcessor == null) {
            return null;
        }
        RsProcessor newRsProcessor;
        try {
            newRsProcessor = rsProcessor.getClass().getConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new SQLException(e);
        } catch (IllegalAccessException e) {
            throw new SQLException(e);
        } catch (InvocationTargetException e) {
            throw new SQLException(e);
        } catch (NoSuchMethodException e) {
            throw new SQLException(e);
        }
        return newRsProcessor.process(rs, this, entity);
    }

    public void reset() {
        copy = new HashMap<String, RsProcessor>(map);
    }
}
